import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import VideosView from '../views/VideosView.vue'
import MembershipView from '../views/MembershipView.vue'
import { authService } from '../services/auth.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      // 未登录时才能访问登录页面
      beforeEnter: (to, from, next) => {
        if (authService.isLoggedIn()) {
          next('/')
        } else {
          next()
        }
      }
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
      // 未登录时才能访问注册页面
      beforeEnter: (to, from, next) => {
        if (authService.isLoggedIn()) {
          next('/')
        } else {
          next()
        }
      }
    },
    // 添加一个需要认证的示例路由
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/ProfileView.vue'),
      // 需要认证才能访问
      meta: { requiresAuth: true }
    },
    {
      path: '/videos',
      name: 'videos',
      component: VideosView,
      meta: { title: '视频教程' }
    },
    {
      path: '/membership',
      name: 'membership',
      component: MembershipView,
      meta: { 
        title: '会员与充值',
        requiresAuth: true 
      }
    }
  ],
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (authService.isLoggedIn()) {
      next()
    } else {
      // 未登录时重定向到登录页面
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存用户想要访问的页面
      })
    }
  } else {
    next()
  }
})

export default router
